package com.lottery.game.controller.v2.upload;


import com.lottery.game.annotation.Current;
import com.lottery.game.common.Response;
import com.lottery.game.common.utils.ImgUtils;
import com.lottery.game.constants.RespErrorCodes;
import com.lottery.game.core.configuration.SftpUtils;
import com.lottery.game.core.model.dto.UserToken;
import com.lottery.game.core.modules.entity.user.GameUser;
import com.lottery.game.core.modules.service.app.GameUserService;

import com.lottery.game.core.modules.service.game.SysDictService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;

import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;

/**
 * 处理图片上传类
 *
 * @author Administrator
 */
@Slf4j
@Controller
@RequestMapping(value = "/api/v2/")
@Api(tags = "APP-图片服务器")
public class UploadController {


    private static final String IMG = "img";

    private String imageServerAddress;

    @Autowired
    private SftpUtils sftpUtils;
    @Autowired
    private GameUserService gameUserService;
    @Autowired
    private SysDictService sysDictService;


    @SuppressWarnings("unchecked")
    @ApiOperation(value = "更新头像-ok", notes = "更新头像，请求报文header里面带上令牌ticket", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value="文件",allowMultiple = true, dataType = "MultipartFile",required = true),
            @ApiImplicitParam(name = "ticket", value = "令牌ticket", paramType = "header",required = true)
    })
    @ApiResponses(value =
            {@ApiResponse(code = 200, message = "successful operation", response = Response.class)}
    )
    @PostMapping(value = "/user/face/update", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Response<String> uploadImg(@ApiIgnore @Current UserToken ticket,
                                      @RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request) {


        try {
            log.info("uploadImg更新头像");
            java.lang.String userId = ticket.getId();
            java.lang.String newFileName = ImgUtils.getFileName(file.getOriginalFilename(),"");

            StringBuffer path = new StringBuffer();
            path
                    .append(ImgUtils.HEADIMG_PATH)
                    .append(LocalDate.now().format(ImgUtils.YEAR_MONTH_FORMATTER))
                    .append("/");

            String imgPath = path.toString();
            GameUser gameUser = gameUserService.get(userId);
            String photourl = gameUser.getPhotourl();
            String fileInfo = sftpUtils.getAppPath() + "/"+ photourl;
            sftpUtils.uploadFileApp(imgPath, newFileName, file.getInputStream());
            int num = gameUserService.updatePhotoAddress(userId, imgPath+newFileName);
            if (num > 0) {
                if ( null != photourl && !photourl.contains("defaultGameUser")) {
                    // 删除非默认头像的服务器上面的图片
                    sftpUtils.deleteFile(fileInfo);
                }
                //构造给前端
                imgPath = imgPath+newFileName;
                String imageServer = this.getImageServer();
                return Response.build(imageServer+imgPath);
            } else {
                return Response.buildError();
            }
        } catch (Exception e) {
            log.error(RespErrorCodes.UNKNOWN_ERROR.errorCode(), e);
            return Response.buildError();
        }
    }

    @SuppressWarnings("unchecked")
    @ApiOperation(value = "上传聊天图片-ok", notes = "上传聊天图片-返回图片地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value="文件",allowMultiple = true, dataType = "MultipartFile",required = true),
            @ApiImplicitParam(name = "ticket", value = "令牌ticket", dataType = "String", paramType = "header",required = true),
    })
    @ApiResponses(value =
            {@ApiResponse(code = 200, message = "successful operation", response = String.class)}
    )

    @PostMapping(value = "/chat/img/upload",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Response<String> uploadChatImg(
            @RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request, @ApiIgnore @Current UserToken userToken) {
        log.info("uploadChatImg上传聊天图片...");
        try {
            String newFileName = ImgUtils.getFileName(file.getOriginalFilename(),"");
            StringBuffer path = new StringBuffer();
            path
                    .append(ImgUtils.CHATIMG_PATH)
                    .append(LocalDate.now().format(ImgUtils.YEAR_MONTH_FORMATTER))
                    .append("/");

            String imgPath = path.toString();
            sftpUtils.uploadFileApp(imgPath, newFileName, file.getInputStream());
            imgPath = imgPath+newFileName;
            //构造给前端
            String imageServer = this.getImageServer();
            return Response.build(imageServer+imgPath);
        } catch (Exception e) {
            log.error(RespErrorCodes.UNKNOWN_ERROR.errorCode(), e);
            return Response.buildError();
        }
    }

    private String getImageServer() {
        if (imageServerAddress != null) {
            return imageServerAddress;
        }
        return imageServerAddress = sysDictService.findImageServerAddress();
    }



}
